package app.dws;


import Bean.TrafficPageViewBean;
import app.dwd.BaseAppV1;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;

import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import org.apache.flink.util.Collector;
import util.AtguiguUtil;
import util.FlinkSinkUtil;

import java.time.Duration;

public class Dws_DwsTrafficVcChArIsNewPageViewWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_DwsTrafficVcChArIsNewPageViewWindow().init(
                4002,
                2,
                "Dws_DwsTrafficVcChArIsNewPageViewWindow",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 封装到一个 pojo 中
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream=parseToPojo(stream);
        // 2. 开窗聚和
        SingleOutputStreamOperator<TrafficPageViewBean> resulStream=windowAndAgg(beanStream);
        // 3. 写出到 clickhouse 中
        writeToClickhouse(resulStream);
    }
    // 3. 写出到 clickhouse 中
    private void writeToClickhouse(SingleOutputStreamOperator<TrafficPageViewBean> resulStream) {
        resulStream
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_vc_ch_ar_is_new_page_view_window",
                        TrafficPageViewBean.class));
    }

    // 2. 开窗聚和
    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficPageViewBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((bean,ts)->bean.getTs())
                        .withIdleness(Duration.ofMillis(1))
                )
                .keyBy(bean -> bean.getCh()+"_"+bean.getAr()+"_"+bean.getVc()+"_"+bean.getIsNew())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TrafficPageViewBean>() {
                            @Override
                            public TrafficPageViewBean reduce(TrafficPageViewBean value1, TrafficPageViewBean value2) throws Exception {
                                value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                                value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                                value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                                value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                                return value1;
                            }
                        },
                        new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                            @Override
                            public void process(String key, Context ctx, Iterable<TrafficPageViewBean> elements, Collector<TrafficPageViewBean> out) throws Exception {
                                TrafficPageViewBean bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);
                            }
                        });
    }

    // 1. 封装到一个 pojo 中
    private SingleOutputStreamOperator<TrafficPageViewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {
                    private ValueState<String> dateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        dateState=getRuntimeContext().getState(
                                new ValueStateDescriptor<String>("dateState",String.class));
                    }

                    @Override
                    public TrafficPageViewBean map(JSONObject obj ) throws Exception {
                        JSONObject common = obj.getJSONObject("common");
                        JSONObject page = obj.getJSONObject("page");

                        String vc = common.getString("vc");
                        String ar = common.getString("ar");
                        String ch = common.getString("ch");
                        String isNew = common.getString("is_new");
                        Long ts = obj.getLong("ts");

                        Long pvCt=1L;
                        Long durSum = page.getLong("during_time");

                        Long svCt=0L;
                        String lastPageId = page.getString("last_page_id");
                        if (lastPageId == null || lastPageId.length() == 0) {
                            svCt=1L;
                        }

                        Long uvCt=0L;
                        String date = dateState.value();
                        String today = AtguiguUtil.toDate(ts);
                        if (!today.equals(date)) {
                            dateState.update(today);
                            uvCt=1L;
                        }

                        return new TrafficPageViewBean("","",vc,ch,ar,isNew,uvCt,svCt,pvCt,durSum,ts);
                    }
                });
    }
}
